package com.mrx.xcitools.controller;

import com.mrx.xcitools.model.JarExecuteConfig;
import com.mrx.xcitools.model.JarFileInfo;
import com.mrx.xcitools.service.FileUploadService;
import com.mrx.xcitools.service.JarFileManageService;
import com.mrx.xcitools.service.ProcessManageService;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author Mr.X
 * @since 2024-03-11 下午 2:32:37
 */
@CrossOrigin
@RestController
@RequestMapping("/jarManage")
public class JarManageController {

    @Resource
    private FileUploadService fileUploadService;

    @Resource
    private JarFileManageService jarFileManageService;

    @Resource
    private ProcessManageService processManageService;

    @PostMapping("/upload")
    public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            if (file.isEmpty() || !StringUtils.hasText(fileName)) {
                return ResponseEntity.badRequest().body("请选择需要上传的文件");
            }
            fileUploadService.uploadJar(file, fileName);
            return ResponseEntity.ok("文件上传成功");
        } catch (IOException e) {
            return ResponseEntity.internalServerError().body("文件上传失败: " + e.getMessage());
        }
    }

    @PostMapping("/execute")
    public Object execute(@RequestBody JarExecuteConfig jarExecuteConfig) {
        File jarFile = jarFileManageService.getJarFile(jarExecuteConfig.getJarName());
        return processManageService.runProcess(jarFile, jarExecuteConfig.getStartArgs());
    }

    @PostMapping("/stopJar")
    public Object stopJar(@RequestBody JarExecuteConfig jarExecuteConfig) {
        return processManageService.stopProcess(jarExecuteConfig.getJarName());
    }

    @PostMapping("/delJar")
    public Object delJar(@RequestBody JarExecuteConfig jarExecuteConfig) {
        return jarFileManageService.delJar(jarExecuteConfig.getJarName());
    }

    @GetMapping("/listAll")
    public List<JarFileInfo> listAllJars() {
        return jarFileManageService.listAll();
    }

    @GetMapping("/getLogs")
    public String getLogs(@RequestParam String jarName, @RequestParam String logFile, @RequestParam Integer lines) {
        return processManageService.getLog(jarName, logFile, lines);
    }

}
